package cn.edu.dlut.ssdut.foodCredit2012.service;

/*import java.util.List;

import org.hibernate.Query;*/
import org.hibernate.Session;

import cn.edu.dlut.ssdut.foodCredit2012.model.ExportCollection;
import cn.edu.dlut.ssdut.foodCredit2012.util.HibernateUtil;

public class ExportCollectionService {
	
	public void add(ExportCollection ex) throws Exception {
		if(!hasExport(ex)){
			Session session = HibernateUtil.getCollectionSessionFactory().getCurrentSession();
			session.beginTransaction();
			session.save(ex);
			session.getTransaction().commit();
		}
	}
	
	public void delete(ExportCollection ex) throws Exception {
		if(hasExport(ex)){
			Session session = HibernateUtil.getCollectionSessionFactory().getCurrentSession();
			session.beginTransaction();
			session.delete(ex);
			session.getTransaction().commit();
		}
	}
	
	public void update (ExportCollection ex)throws Exception{
		if(hasExport(ex)){
			Session session = HibernateUtil.getCollectionSessionFactory().getCurrentSession();
			session.beginTransaction();
			session.update(ex);
			session.getTransaction().commit();
		}
	}
	
	/*public List exportList() {
		List exportList = null;
		Session session = HibernateUtil.getUserSessionFactory().getCurrentSession();
		session.beginTransaction();
		
		Query query = session.createQuery("from Export");
		query.setFirstResult(2);
		query.setMaxResults(10);
		exportList = query.list();
		
		session.getTransaction().commit();		
		return exportList;
	}*/
	
	public boolean hasExport(ExportCollection ex) throws Exception {
		Session session = HibernateUtil.getCollectionSessionFactory().getCurrentSession();
		session.beginTransaction();
		long count = (Long)session.createQuery("select count(*) from ExportCollection ex where ex.licenceID = :licenceID")
			.setString("licenceID", ex.getLicenceID())
			.uniqueResult();
		session.getTransaction().commit();
		
		if(count > 0) return true;
		return false;
		
	}
	
	public ExportCollection load(ExportCollection ex) throws Exception{
		if(hasExport(ex)){
			ex = loadByLicenceID(ex.getLicenceID());
			return ex;
		}
		return ex;
	}
	
	public ExportCollection loadByLicenceID(String licenceID) throws Exception{
		ExportCollection ex = new ExportCollection();
		Session session = HibernateUtil.getCollectionSessionFactory().getCurrentSession();
		session.beginTransaction();
		
		ex = (ExportCollection)session.createQuery("select ex from ExportCollection ex where ex.licenceID = :licenceID")
			.setParameter("licenceID", licenceID)
			.uniqueResult();
		session.getTransaction().commit();
		return ex;
	}

}
